package com.appBase.tools;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * Created on 2021/3/18 9:53
 *
 * @author yuliang
 */
public class FileUtil {
    /**
     * 获取文件
     * @return
     */
    public static String getFileContent(String filePath ,String fileName) {
        String content = "";
        String path = filePath + "/" +fileName;
        File file = new File(path);
        try {
            InputStream inputStream = new FileInputStream(file);
            if (inputStream != null){
                InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
                BufferedReader bufferedReader = new BufferedReader(reader);

                String line;
                while ((line = bufferedReader.readLine()) != null){
                    content += line;
                }
                inputStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }

    public static void setFileContent(String filePath ,String fileName, String content) {
        File dir = new File(filePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File file = new File(dir, fileName);
        file.setWritable(true);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            fos.write(content.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
